﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Transactions;

[System.Security.Permissions.PrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Authenticated = true, Role = "DomainStaff")]
public partial class IsaRules : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
	}

	protected void ruleList_SelectedIndexChanged(object sender, EventArgs e)
	{
		if (ruleList.SelectedValue == "-1") return;

		using (var isa = new IsaDataClassesDataContext())
		{
			var ruleinfo = isa.RuleInfos.Single(r => r.ruleid == int.Parse(ruleList.SelectedValue));

			if (ruleinfo.isactive)
				activeList.SelectedIndex = 1;
			else
				activeList.SelectedIndex = 0;
			if (ruleinfo.isactive && ruleinfo.autoclear.HasValue)
				expirytimeText.Text = ruleinfo.autoclear.Value.ToShortTimeString();
			else
				expirytimeText.Text = DateTime.Now.AddHours(1).ToShortTimeString();

			expirytimeText.Focus();
		}
	}

	protected void saveBut_Click(object sender, EventArgs e)
	{
		if (ruleList.SelectedValue == "-1") return;

		TimeSpan ts;
		if (!TimeSpan.TryParse(expirytimeText.Text, out ts) || ts < DateTime.Now.TimeOfDay)
		{
			expirytimeText.Text = DateTime.Now.AddHours(1).ToShortTimeString();
			HtmlHelpers.PopUpMsg(this, "expiry", "Invalid expiry time. Use 24 hour format HH:MM");
			return;
		}

		using (var isa = new IsaDataClassesDataContext())
		{
			var req = new PendingChange();
			req.username = "username";
			req.ruleid = int.Parse(ruleList.SelectedValue);
			req.newstate = (activeList.SelectedIndex == 0);
			if (expirytimeText.Text.Length > 0)
				req.expires = DateTime.Now.Date.Add(ts);
			else
				req.expires = DateTime.Now;		// junk value

			isa.PendingChanges.InsertOnSubmit(req);
			isa.SubmitChanges();
		}

		// signal to WCF service there is something to check
		using (var client = new IsaServiceReference.IsaInterfaceClient())
		{
			client.DoPending();
		}

		expirytimeText.Text = null;

		Response.Redirect("IsaRules.aspx");
	}

	protected string GetActiveImage(object Container)
	{
		bool status = (bool)DataBinder.Eval(Container, "DataItem.isactive");
		if (status)
				return "red.gif";
		else
				return "gre.gif";
	}

	protected void ruleList_DataBound(object sender, EventArgs e)
	{
		ruleList.Items.Insert(0, new ListItem("(choose)", "-1"));
	}
}
